package com.example.contentresolvertest

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_contact.*
import java.util.ArrayList

class ContactActivity : AppCompatActivity() {

    private val contactsList = ArrayList<String>()
    private lateinit var adapter: ArrayAdapter<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_contact)

        //android.R.layout.simple_list_item_1 这是android内置的一个list_item只包含一个textview
        adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,contactsList)
        contactsView.adapter = adapter
        //如果没有申请权限，申请
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
            != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS),1)
        }
        else{
            readContacts()
        }
    }

    /**
     * 权限申请结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,   //请求码
        permissions: Array<out String>, //请求权限
        grantResults: IntArray  //请求结果
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            1 -> {
                //如果不为空且同意
                if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    readContacts()
                }
                else{
                    Toast.makeText(this, "你拒绝了权限！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 查询联系人
     */

    @SuppressLint("Range")
    private fun readContacts(){
        //查询参数：URI 指定从某一应用下的某一张表查询，Projection 指定查询的列 selection 查询where的约束条件
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //返回一个游标，使用apply查询
            contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,null,null)?.apply {
                while (moveToNext()){
                    //获取联系人姓名
                    val displayName = getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
                    //获取联系人手机号
                    val number = getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                    contactsList.add("$displayName\n$number")
                }
                //通知适配器数据已经改变
                adapter.notifyDataSetChanged()
                //关闭查询
                close()
            }
        }
    }
}